package com.chen.hotel.controller;


import com.chen.hotel.Service.UserService;
import com.chen.hotel.VO.ResultVO;
import com.chen.hotel.annotation.LoginToken;
import com.chen.hotel.converter.User2UserDTO;
import com.chen.hotel.domain.Users;
import com.chen.hotel.dto.UserDTO;
import com.chen.hotel.enums.AuthEnum;
import com.chen.hotel.exception.HotelException;
import com.chen.hotel.form.LoginForm;
import com.chen.hotel.utils.ResultVOUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

@CrossOrigin
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("")
    @LoginToken(auth = AuthEnum.SUPER)
    public ResultVO createUser(@RequestBody Users users){
        Users u = this.userService.create(users);
        return ResultVOUtil.success(User2UserDTO.convert(u));
    }

    @PostMapping("/login")
    public ResultVO login(@Valid @RequestBody LoginForm form, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            throw new HotelException(401, bindingResult.getFieldError().getDefaultMessage());
        }
        String token = this.userService.login(form);
        if(token == null){
            throw new HotelException(400, "用户名或密码错误");
        }
        return ResultVOUtil.success(token);
    }


    @PatchMapping("/{id}")
    @LoginToken
    public ResultVO update(@PathVariable Integer id, @RequestBody Users users){
        users.setId(id);
        return ResultVOUtil.success(
                User2UserDTO.convert(
                        this.userService.update(users)
                )
        );
    }

    /**
     * 删除管理员用户: 超级管理员的权限
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    @LoginToken(auth = AuthEnum.SUPER)
    public ResultVO delete(@PathVariable Integer id){
        this.userService.delete(id);
        return ResultVOUtil.success(null);
    }

    /**
     * 获取当前登录用户的信息
     */
    @GetMapping("")
    @LoginToken
    public ResultVO getUser(HttpServletRequest request){
        // 读取出拦截器中处理后的userid
        Integer userid = (Integer) request.getAttribute("userid");
        return ResultVOUtil.success(
                User2UserDTO.convert(
                        this.userService.findById(userid)
                )
        );
    }

}
